import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from './constants';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor() {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            ignoreExpiration: false,
            secretOrKey: jwtConstants.secret,
        });
    }

   // token验证, payload是super中曾经解析好的token信息
    async validate(payload: any) {
        //因为已经验证过token了所以在payload中进行验证用户信息是否为空
        if (!payload.username || !payload.userId) {
            return false;
        }
        return { userId: payload.userId, username: payload.username };
    }
}
